#!/usr/bin/python

import os
import sys
import time

def runCmd(job, schema):
    schema = schema.rstrip()
    if job == 'update':
        command = './update data/'+schema+'.root data/'+schema+'_temp.root dsds &'
    elif job == 'seed':
        command = './kSeeder data/'+schema+'.root data/'+schema+'_seed.root > log &'
    elif job == 'track':
        command = './kTracker_multi data/'+schema+'_seed.root data/'+schema+'_track.root > log_track_'+schema+' &'
    elif job == 'vertex':
        command = './kVertex data/'+schema+'_track.root data/'+schema+'_vertex.root > log_vertex_'+schema+' &'
    elif job == 'vertexfast':
        command = './kVertex_fast data/'+schema+'_fast.root data/'+schema+'_vertex_fast.root > log_vertex_'+schema+' &'
    elif job == 'fast':
        command = './kFastTracking data/'+schema+'.root data/'+schema+'_fast.root > log_fast_'+schema+' &'
    elif job == 'read':
        command = './sqlDataReader '+schema+' data/'+schema+'.root'
    print command
    os.system(command)

fin = open(sys.argv[2], 'r')
schemas = fin.readlines()

exe_name = {}
exe_name['update'] = 'update'
exe_name['seed']   = 'kSeeder'
exe_name['track']  = 'kTracker_multi'
exe_name['vertex'] = 'kVertex'
exe_name['vertexfast'] = 'kVertex_fast'
exe_name['fast']   = 'kFastTracking'
exe_name['read']   = 'sqlDataReader'

nJobsMax = 6
if len(sys.argv) > 3:
    nJobsMax = int(sys.argv[3])

nSubmitted = 0
while nSubmitted < len(schemas):
    nRunning = int(os.popen('ps | grep '+exe_name[sys.argv[1]]+' | wc -l').read().strip())
    print(sys.argv[1]+': '+str(nSubmitted)+" submitted, "+str(nRunning)+' running ...' )
    for i in range(nRunning, nJobsMax):
        runCmd(sys.argv[1], schemas[nSubmitted])
	nSubmitted = nSubmitted + 1
        
	if nSubmitted >= len(schemas): break

    time.sleep(60)

while nRunning != 0:
    time.sleep(30)
    nRunning = int(os.popen('ps | grep '+exe_name[sys.argv[1]]+' | wc -l').read().strip())
    print(sys.argv[1]+': '+str(nSubmitted)+" submitted, "+str(nRunning)+' running ...' )
